<?php

require_once 'BasicController.php';

class UserController extends Zend_Controller_Action
{

	public function init()
	{
		/* Initialize action controller here */
	}

	public function indexAction()
	{
		// action body
	}

	//CADASTRA NOVO USUARIO NO SISTEMA
	public function createUserAction()
	{

		$userBusiness = new UserBusiness();

		$email = $this->_request->getParam('email');

		if($_GET){
			$user = array(
			    	"email"		=> $email,
			);

			$existUser = $userBusiness->getUserByEmail($email);

			if($existUser != null){
				$errors['email'] = "E-mail já cadastrado no sistema.";
				$this->view->errorMessages = $errors;
			}

			$this->view->form = $user;
		}

		if($_POST){

			$validator = new ClientValidator();

			try{
				$user = array(
			    	"name" 		=> $this->_request->getParam('name'),
			    	"login" 	=> $this->_request->getParam('login'),
					"birth" 	=> $this->_request->getParam('birth'),
			    	"gender" 	=> $this->_request->getParam('gender'),
			    	"cpf" 		=> $this->_request->getParam('cpf'),
			    	"phone" 	=> $this->_request->getParam('phone'),
			    	"celphone" 	=> $this->_request->getParam('celphone'),
			    	"email"		=> $this->_request->getParam('email'),
			    	"password"	=> $this->_request->getParam('pass'),
					"user_type"	=> 1,
					"flag_mail" => ($this->_request->getParam('flagmail') == 1) ? 1 : 0,
				);
					
				$confirm = $this->_request->getParam('passcon');

				$address = array(
					"cep"		=> $this->_request->getParam('cep'),
					"type"		=> $this->_request->getParam('type'),
					"address"	=> $this->_request->getParam('address'),
					"number"	=> $this->_request->getParam('number'),
					"comp"		=> $this->_request->getParam('comp'),
					"neigh"		=> $this->_request->getParam('neigh'),
					"city"		=> $this->_request->getParam('city'),
					"state"		=> $this->_request->getParam('state'),
					"reference"	=> $this->_request->getParam('reference'),
				);
					
				//valida o formulario de cadastro
				$errors = $validator->newClientValid($user, $confirm, $address);
					
				if(!empty($errors)){
					$this->view->form = $user;
					$this->view->addForm = $address;
					$this->view->errorMessages = $errors;
				}else{


					$sendMail = new MailBusiness();
					$id_client = $userBusiness->createUser($user, $address);

					$sendMail->sendRegisterMail($user, base64_encode($id_client));

					$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');

					$this->_redirect('/finish/success?message='.$config->register->success);
				}
			}catch (Exception $e){
				echo $e;
			}
		}
			
	}

	//ATIVA USUARIO NO SISTEMA
	public function activeClientAction()
	{
		try{
			$userBusiness = new UserBusiness();
			$id = $this->getRequest()->getParam("active");

			$userBusiness->activeClient(base64_decode($id));
		}catch (Exception $e){
			Zend_Registry::get('log')->info('Erro ao ativar usuário: '.$id, $e);
		}
	}

	public function forgotPasswordAction(){
		if($_POST){
			$userBusiness = new UserBusiness();

			//Recupera os valores informados no form
			$email = $this->_request->getParam('email');

			$userData = $userBusiness->getUserByEmail($email);

			if($userData){

				$pass = $this->geraSenha(8, true, true, false);

				$userBusiness->updatePassword($userData, $pass);

				$sendMail = new MailBusiness();

				$sendMail->sendPasswordMail($userData, $pass);

				$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');

				$this->_redirect('/finish/success?message='.$config->forgot->success);
					
			}else{
				$this->view->login = $email;
				$this->view->authErrorMessage = "Usuário inválido!";
				return;
			}
		}
	}

	//Gera senha a ser enviada por email, $tamanho = int; ($maiusculas, $numeros, $simbolos) = boolean
	function geraSenha($tamanho, $maiusculas, $numeros, $simbolos)
	{
		$lmin = 'abcdefghijklmnopqrstuvwxyz';
		$lmai = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$num = '1234567890';
		$simb = '!@#$%*-';
		$retorno = '';
		$caracteres = '';

		$caracteres .= $lmin;
		if ($maiusculas) $caracteres .= $lmai;
		if ($numeros) $caracteres .= $num;
		if ($simbolos) $caracteres .= $simb;

		$len = strlen($caracteres);
		for ($n = 1; $n <= $tamanho; $n++) {
			$rand = mt_rand(1, $len);
			$retorno .= $caracteres[$rand-1];
		}
		return $retorno;
	}


}





